package com.cinsea.mobile.ext;

import com.alibaba.fastjson.JSON;
import com.cinsea.common.Env;
import com.cinsea.common.ExtAction;
import com.cinsea.common.JdbcDao;
import com.cinsea.common.Page;
import com.cinsea.hrm.service.HumanService;
import com.cinsea.interfaces.form.Formdata;
import com.cinsea.interfaces.form.FormdataServiceImpl;
import com.cinsea.interfaces.model.Cell;
import com.cinsea.interfaces.model.Dataset;
import com.cinsea.security.util.JdbcUtil;
import com.cinsea.util.DateUtil;
import com.cinsea.util.NumberUtil;
import com.cinsea.util.SqlUtil;
import com.cinsea.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: xf
 * Date: 13-7-21
 * Time: 下午5:04
 */
public class CrmAction extends ExtAction {
    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String action = StringUtil.null2String(request.getParameter("action"));
        String key = StringUtil.null2String(request.getParameter("q"));
        int page = NumberUtil.getIntegerValue(request.getParameter("page"), 1);
        JdbcDao jdbcDao = Env.getBean("jdbcDao");
        HumanService humanService = Env.getBean("humanService");
        if (action.equals("getcrmlist")) {
            StringBuffer sql = new StringBuffer("select id,name,managerid from ut_customerinfo where deleted=0 and 1=1 ");
            ArrayList sqlparam = new ArrayList();
            if (!StringUtil.isEmpty(key)) {
                sql.append(" and name like ?");
                sqlparam.add("%" + key + "%");
            }
            sql.append(" order by modifydatetime desc ");
            String[] _sql = JdbcUtil.getPermissionSql(sql.toString(), "ut_customerinfo", sqlparam);
            Page pageObject = jdbcDao.pagedQuery(_sql[0], StringUtil.string2Array(_sql[1], ","), page, 10);
            if (pageObject.getTotalSize() != 0) {
                List<Map> result = (List) pageObject.getResult();
                List jsonlist = new ArrayList();
                for (Map obj : result) {
                    Map rowdata = new HashMap();
                    rowdata.put("id", obj.get("id"));
                    rowdata.put("processid", obj.get("id"));
                    rowdata.put("title", obj.get("name"));
                    String managerName = humanService.getHumanNamesByIds(obj.get("managerid").toString());
                    rowdata.put("manager", managerName);
                    jsonlist.add(rowdata);
                }
                Map object = new HashMap();
                object.put("totalCount", pageObject.getTotalSize());
                object.put("result", jsonlist);
                gzip(request,response,JSON.toJSONString(object));
            } else {
                Map object = new HashMap();
                object.put("totalCount", 0);
                response.getWriter().print(JSON.toJSONString(object));
            }
        }
        if (action.equals("getcrmfavor")) {
            StringBuffer sql = new StringBuffer("select id,name,managerid from ut_customerinfo where deleted=0 and 1=1 and id in (select objid from cs_favorite where humanid=?)");

            sql.append(" order by modifydatetime desc ");
            Page pageObject = jdbcDao.pagedQuery(sql.toString(), new Object[]{Env.getRemoteUser().getId()}, page, 10);
            if (pageObject.getTotalSize() != 0) {
                List<Map> result = (List) pageObject.getResult();
                List jsonlist = new ArrayList();
                for (Map obj : result) {
                    Map rowdata = new HashMap();
                    rowdata.put("id", obj.get("id"));
                    rowdata.put("processid", obj.get("id"));
                    rowdata.put("title", obj.get("name"));
                    String managerName = humanService.getHumanNamesByIds(obj.get("managerid").toString());
                    rowdata.put("manager", managerName);
                    jsonlist.add(rowdata);
                }
                Map object = new HashMap();
                object.put("totalCount", pageObject.getTotalSize());
                object.put("result", jsonlist);
                gzip(request,response,JSON.toJSONString(object));

            } else {
                Map object = new HashMap();
                object.put("totalCount", 0);
                response.getWriter().print(JSON.toJSONString(object));
            }
        }
        if (action.equals("getcontactor")) {
            StringBuffer sql = new StringBuffer("select id,name,title,cell,tel from ut_contact where deleted=0 and 1=1 and crmid=?");

            sql.append(" order by modifydatetime desc ");
            Page pageObject = jdbcDao.pagedQuery(sql.toString(), new Object[]{key}, page, 10);
            if (pageObject.getTotalSize() != 0) {
                List<Map> result = (List) pageObject.getResult();
                List jsonlist = new ArrayList();
                for (Map obj : result) {
                    Map rowdata = new HashMap();
                    rowdata.put("id", obj.get("id"));
                    rowdata.put("processid", obj.get("id"));
                    rowdata.put("name", obj.get("name"));
                    rowdata.put("title", obj.get("title"));
                    rowdata.put("cell", obj.get("cell"));
                    rowdata.put("tel", obj.get("tel"));
                    jsonlist.add(rowdata);
                }
                Map object = new HashMap();
                object.put("totalCount", pageObject.getTotalSize());
                object.put("result", jsonlist);
                gzip(request,response,JSON.toJSONString(object));
            } else {
                Map object = new HashMap();
                object.put("totalCount", 0);
                response.getWriter().print(JSON.toJSONString(object));
            }
        }
        if (action.equals("getcontactlist")) {
            String type = StringUtil.null2String(request.getParameter("type"));
            StringBuffer sql = new StringBuffer("select id,content,lxer,lxdate from ut_contactlist where deleted=0 and 1=1 ");
            ArrayList sqlparam = new ArrayList();
            if (!StringUtil.isEmpty(key)) {
                if(type.equals("customer"))
                sql.append(" and crmid= ?");
                else
                sql.append(" and sjid= ?");
                sqlparam.add(key);
            }
            sql.append(" order by modifydatetime desc ");
            Page pageObject = jdbcDao.pagedQuery(sql.toString(), sqlparam.toArray(), page, 10);
            if (pageObject.getTotalSize() != 0) {
                List<Map> result = (List) pageObject.getResult();
                List jsonlist = new ArrayList();
                for (Map obj : result) {
                    Map rowdata = new HashMap();
                    rowdata.put("id", obj.get("id"));
                    rowdata.put("processid", obj.get("id"));
                    rowdata.put("title", obj.get("content"));
                    rowdata.put("lxdate", obj.get("lxdate"));
                    String lxerName = humanService.getHumanNamesByIds(obj.get("lxer").toString());
                    rowdata.put("lxer", lxerName);
                    jsonlist.add(rowdata);
                }
                Map object = new HashMap();
                object.put("totalCount", pageObject.getTotalSize());
                object.put("result", jsonlist);
                gzip(request,response,JSON.toJSONString(object));
            } else {
                Map object = new HashMap();
                object.put("totalCount", 0);
                response.getWriter().print(JSON.toJSONString(object));
            }
        }
        if (action.equals("getopportunitys")) {
            StringBuffer sql = new StringBuffer("select id,name,crmid from ut_opportunities where deleted=0 and 1=1 ");
            ArrayList sqlparam = new ArrayList();
            if (!StringUtil.isEmpty(key)) {
                sql.append(" and cgrates= ?");
                sqlparam.add(key);
            }
            sql.append(" order by modifydatetime desc ");
            String[] _sql = JdbcUtil.getPermissionSql(sql.toString(), "ut_customerinfo", sqlparam);
            Page pageObject = jdbcDao.pagedQuery(_sql[0], StringUtil.string2Array(_sql[1], ","), page, 10);
            if (pageObject.getTotalSize() != 0) {
                List<Map> result = (List) pageObject.getResult();
                List jsonlist = new ArrayList();
                for (Map obj : result) {
                    Map rowdata = new HashMap();
                    rowdata.put("id", obj.get("id"));
                    rowdata.put("processid", obj.get("id"));
                    rowdata.put("name", obj.get("name"));
                    rowdata.put("customer", jdbcDao.queryForObject("select name from ut_customerinfo where id=? ",new Object[]{obj.get("crmid")},String.class));
                    jsonlist.add(rowdata);
                }
                Map object = new HashMap();
                object.put("totalCount", pageObject.getTotalSize());
                object.put("result", jsonlist);
                gzip(request,response,JSON.toJSONString(object));
            } else {
                Map object = new HashMap();
                object.put("totalCount", 0);
                response.getWriter().print(JSON.toJSONString(object));
            }
        }
        if (action.equals("savecontact")) {
            String content = StringUtil.null2String(request.getParameter("content"));
            String processid = StringUtil.null2String(request.getParameter("processid"));
            String type = StringUtil.null2String(request.getParameter("type"));
            String lxer = Env.getRemoteUser().getId();
            String lxdate = DateUtil.getCurrentDate();
            FormdataServiceImpl si = new FormdataServiceImpl();
            Formdata formdata = new Formdata();
            formdata.setOperator(Env.getRemoteUser().getId());
            formdata.setTypeid("402881e43d1436e5013d15607f6c00dd"); //contact目录
            String crmid = "";
            Dataset ds = new Dataset();
            List<Cell> mainlist = new ArrayList(); //主表单元格
            Cell c1 = new Cell();
            c1.setId("ut_contactlist_content");
            c1.setValue(content);
            Cell c2 = new Cell();
            c2.setId("ut_contactlist_lxer");
            c2.setValue(lxer);
            Cell c3 = new Cell();
            c3.setId("ut_contactlist_lxdate");
            c3.setValue(lxdate);
            if (type.equals("customer")) {
                crmid = processid;
                Cell c4 = new Cell();
                c4.setId("ut_contactlist_crmid");
                c4.setValue(processid);
                mainlist.add(c4);
            } else if (type.equals("opportunity")) {
                Cell c4 = new Cell();
                c4.setId("ut_contactlist_sjid");
                c4.setValue(processid);
                mainlist.add(c4);
                crmid = (String) jdbcDao.queryForObject("select crmid from ut_opportunities where processid=?", new Object[]{processid}, String.class);
                Cell c5 = new Cell();
                c5.setId("ut_contactlist_crmid");
                c5.setValue(crmid);
                mainlist.add(c5);
            } else {
                response.getWriter().print("{\"success\":false}");
                return;
            }
            mainlist.add(c1);
            mainlist.add(c2);
            mainlist.add(c3);
            Map share = jdbcDao.queryForMap("select managerid,dqid,salesid from ut_customerinfo where  processid=?", new Object[]{crmid});
            Cell c6 = new Cell();
            c6.setId("ut_contactlist_managerid");
            c6.setValue(StringUtil.null2String(share.get("managerid")));
            mainlist.add(c6);
            Cell c7 = new Cell();
            c7.setId("ut_contactlist_khssdq");
            c7.setValue(StringUtil.null2String(share.get("dqid")));
            mainlist.add(c7);
            Cell c8 = new Cell();
            c8.setId("ut_contactlist_gongxiang");
            c8.setValue(StringUtil.null2String(share.get("salesid")));
            mainlist.add(c8);
            ds.setMaintable(mainlist);
            formdata.setData(ds);
            si.createFormdata(formdata);
            response.getWriter().print("{\"success\":true}");
        }
    }
}
